package com.scanner.hardware.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.scanner.bean.BrocastButton;
import com.scanner.bean.ScanSetting;
import com.scanner.hardware.R;
import com.scanner.util.SharePreConfig;
import com.google.gson.Gson;
import com.suke.widget.SwitchButton;

import java.util.List;

/**
 * Created by UglyB
 * 0n 2019/5/8
 */
public class ButtonAdapter extends BaseAdapter {

    private Context context;
    private List<BrocastButton> list;
    private final ScanSetting setting;

    public ButtonAdapter(Context context, List<BrocastButton> list){
        this.context = context;
        this.list = list;
        String scanSetting = SharePreConfig.getScanSetting();
        Gson gson = new Gson();
        setting = gson.fromJson(scanSetting, ScanSetting.class);
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        ButtonViewHolder viewHolder = null;
        if(view == null){
            viewHolder = new ButtonViewHolder();
            view = LayoutInflater.from(context).inflate(R.layout.item_button_layout,null);
            viewHolder.tvBtnKeyName = view.findViewById(R.id.tv_btnKeyName);
            viewHolder.sbBtnKey = view.findViewById(R.id.sb_btnKey);
            view.setTag(viewHolder);
        }else {
            viewHolder = (ButtonViewHolder) view.getTag();
        }

        viewHolder.tvBtnKeyName.setText(list.get(position).getId());
        viewHolder.sbBtnKey.setChecked(Boolean.parseBoolean(list.get(position).getValue()));
        viewHolder.sbBtnKey.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                list.get(position).setValue(String.valueOf(isChecked));
                setting.setBrocastButtons(list);
                SharePreConfig.setScanSetting(new Gson().toJson(setting));
            }
        });
        return view;
    }


    class ButtonViewHolder {
        TextView tvBtnKeyName;
        SwitchButton sbBtnKey;
    }



}
